import SparkMD5 from 'spark-md5';

// 定义 Merkle 树节点的类
class MerkleNode {
  constructor(hash, left = null, right = null) {
    this.h = hash;
    this.l = left;
    this.r = right;
  }
}

// 定义 Merkle 树的类
export class MerkleTree {
  constructor(nodes) {
    if (nodes.length === 0) {
      throw new Error('Empty Nodes');
    }
    if (typeof nodes[0] === 'string') {
      this.leafs = nodes.map(node => new MerkleNode(node));
    } else {
      this.leafs = nodes;
    }
    this.root = this.buildTree();
  }

  getRootHash() {
    return this.root.h;
  }

  buildTree() {
    let currentLevelNodes = this.leafs;
    while (currentLevelNodes.length > 1) {
      const parentNodes = [];
      for (let i = 0; i < currentLevelNodes.length; i += 2) {
        const left = currentLevelNodes[i];
        const right = i + 1 < currentLevelNodes.length ? currentLevelNodes[i + 1] : null;
        const parentHash = this.calculateHash(left, right);
        parentNodes.push(new MerkleNode(parentHash, left, right));
      }
      currentLevelNodes = parentNodes;
    }

    return currentLevelNodes[0]; // 返回根节点
  }

  calculateHash(left, right) {
    // 如果 right 存在，合并左右节点的哈希值
    if (right) {
      const combinedData = left.h + right.h;
      return SparkMD5.hash(combinedData);
    }
    // 如果只有左节点，返回左节点的哈希值
    return left.h;
  }
}
